package logic

import (
	"context"
	"fmt"
	"houses/housesrpc/housesrpc"
	"houses/housesrpc/internal/svc"
	"houses/model/cache"
	"houses/model/mysql"
	"houses/pkg"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginUserLogic {
	return &LoginUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginUserLogic) LoginUser(in *housesrpc.LoginUserRequest) (*housesrpc.RLoginUserUserResponse, error) {
	// todo: add your logic here and delete this line
	var users mysql.User
	mysql.DB.Debug().Where("number=?", in.Number).Find(&users)
	if users.ID == 0 {
		return nil, fmt.Errorf("没有该用户,请注册")
	}

	if users.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("密码错误,请重新输入")
	}

	sendSms, _ := cache.Rdb.Get(l.ctx, "SmsKey"+in.Number).Result()
	if in.SmsCaptcha != sendSms {
		return nil, fmt.Errorf("短信验证码错误,请重新输入")
	}

	captcha, _ := cache.Rdb.Get(l.ctx, "captchaKey"+in.Number).Result()
	if in.Captcha != captcha {
		return nil, fmt.Errorf("图片验证码错误,请重新输入")
	}

	return &housesrpc.RLoginUserUserResponse{
		UserId: int64(users.ID),
	}, nil
}
